﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BigEaterCh.Kontrolki;
using BigEaterCh.Formularze;
using LibreOfficeExport;

namespace BigEaterCh
{
  public partial class FormRozliczenie : FormZywienie
  {
    private DateTime _activeDay;

    public DateTime ActiveDay
    {
      get
      {
        return _activeDay;
      }
      set
      {
        _activeDay = value;
        userDzien1.ActiveDay = dateTimePicker1.Value;
        dateTimePicker1.Value = value;
        RefreshDataPrzychody();
        RefreshDataRozchody();
        RefreshDataStan();
        RefreshRozliczenie();
        Przelicz();
      }
    }

    private static FormRozliczenie _instance;

    public static FormRozliczenie Pokaz(Form parentForm)
    {
      if( _instance != null )
      {
        _instance.RefreshDataPrzychody();
        _instance.RefreshDataRozchody();
        _instance.RefreshDataStan();
        _instance.RefreshRozliczenie();
        _instance.Przelicz();
      }
      else
      {
        _instance = new FormRozliczenie
        {
          MdiParent = parentForm
        };
      }
      return _instance;
    }


    private FormRozliczenie()
    {
      InitializeComponent();
      ActiveDay = DateTime.Today;

      this.dataGridViewTextBoxColumn2.DisplayMember = "Description";
      this.dataGridViewTextBoxColumn18.DisplayMember = "Description";
      this.dataGridViewTextBoxColumn21.DisplayMember = "Description";
    }

    private void DateTimePicker1ValueChanged(object sender, EventArgs e)
    {
      ActiveDay = dateTimePicker1.Value;
    }

    private void ButtonDzienPoprzedniClick(object sender, EventArgs e)
    {
      ActiveDay = dateTimePicker1.Value.AddDays(-1);
    }

    private void ButtonDzienNastepnyClick(object sender, EventArgs e)
    {
      ActiveDay = dateTimePicker1.Value.AddDays(1);
    }

    private void TabControl2SelectedIndexChanged(object sender, EventArgs e)
    {
      if(tabControl2.SelectedTab.Name == tabPagePrzychody.Name)
      {
        RefreshDataPrzychody();
      }
      if (tabControl2.SelectedTab.Name == tabPageRozchody.Name)
      {
        RefreshDataRozchody();
      }
      if (tabControl2.SelectedTab.Name == tabPageStan.Name)
      {
        RefreshDataStan();
      }
      if (tabControl2.SelectedTab.Name == tabPageRozliczenie.Name)
      {
        RefreshRozliczenie();
      }
      Przelicz();

    }

    public void RefreshDataPrzychody()
    {
      var query = from c in FormBigEaterCh.Ze.Przychody
                   where c.Data == _activeDay 
                    select c;

      przychodyBindingSource.DataSource = query;
      produktyBindingSource.DataSource = FormBigEaterCh.Ze.Produkty;
      wzBindingSource.DataSource = FormBigEaterCh.Ze.Wz;
      fakturyBindingSource.DataSource = FormBigEaterCh.Ze.Faktury;
    }

    public void RefreshDataRozchody()
    {
      var query = from c in FormBigEaterCh.Ze.Rozchody
                  where c.Data == _activeDay
                  select c;

      rozchodyBindingSource.DataSource = query;
      produktyBindingSource.DataSource = FormBigEaterCh.Ze.Produkty;
    }

    public void RefreshRozliczenie()
    {

      var query = from c in FormBigEaterCh.Ze.Dni
                  where c.Data == _activeDay
                  select c;
      dniBindingSource.DataSource = query;
      typyPosilkowBindingSource.DataSource = FormBigEaterCh.Ze.TypyPosilkow;

    }

    private void Przelicz()
    {
      var s = from c in FormBigEaterCh.Ze.Rozchody
              where c.Data == this._activeDay
              select c;
      decimal sum=0.0m;
      foreach(var c in s)
      {
        sum += c.Wartosc;
      }

      this.textBoxSumaRozchodow.Text = sum.ToString("C2");

      var sumOsoby = (from c in FormBigEaterCh.Ze.Dni
                      where c.Data == this._activeDay
                      select c.IloscPersonelu).Sum();
      var sumDzieci = ( from c in FormBigEaterCh.Ze.Dni
                        where c.Data == this._activeDay
                        select c.IloscDzieci ).Sum();

      var liczbaPos =  (sumDzieci.HasValue?sumDzieci.Value:0 )+ (sumOsoby.HasValue?sumOsoby.Value:0 );
      if( liczbaPos!=0 )
      {
        decimal posJedn = sum/liczbaPos;
        this.textBoxLiczbaPosilkow.Text = liczbaPos.ToString();
        this.textBoxCenaPosilku.Text = posJedn.ToString("C2");
      }
      else
      {
        this.textBoxLiczbaPosilkow.Text = @"Brak posiłków!";
        this.textBoxCenaPosilku.Text = @"Brak posiłków!";
      }
    }

    void RefreshDataStan()
    {
      RefreshDataStanDate(_activeDay);

      dniProduktyBindingSource.DataSource = from c in FormBigEaterCh.Ze.DniProdukty
                                            where ( c.Data == _activeDay && c.Ilosc!=0)
                                            select c;
    }

    private void PrzeliczNastępne()
    {
      var updlQuery = from c in FormBigEaterCh.Ze.DniProdukty
                      where ( c.Data > _activeDay )
                      orderby c.Data ascending
                      select c.Data;

      if( updlQuery.Count()>0 )
      {
        var distq = updlQuery.Distinct();

        foreach( var date in distq )
        {
          RefreshDataStanDate(date);
        }
      }
    }

    void RefreshDataStanDate(DateTime dt)
    {
      //try
      //{

      FormBigEaterCh.GetDataBase();
      if( FormBigEaterCh.Ze != null )
      {
        var delQuery = from c in FormBigEaterCh.Ze.DniProdukty
                       where ( c.Data == dt )
                    select c;

        foreach(var del in delQuery)
        {
          FormBigEaterCh.Ze.DniProdukty.DeleteObject(del);      
        }


        var query2 = ( from c in FormBigEaterCh.Ze.Przychody
                       join o in FormBigEaterCh.Ze.Produkty on c.IdProduktu equals o.IdProduktu
                       select new
                       {
                         c.IdProduktu,
                         o.Nazwa,
                         o.Jednostka,
                         c.CenaBrutto
                       } ).Distinct();


        var query = from c in FormBigEaterCh.Ze.DniProdukty
                    where ( c.Data < dt )
                    select c.Data;

        DateTime? StartData = null;
        DateTime? StopData = dt;

        if( query.Count()>0 )
        {
          StartData = query.Max();
        }

        if( query2.Count()>0 )
        {
            foreach( var pozycje in query2 )
            {
              decimal pi = 0;
              decimal ri = 0;
              decimal si = 0;
              var p1 = from c in FormBigEaterCh.Ze.Przychody
                       where
                         ( c.IdProduktu == pozycje.IdProduktu && c.Data > StartData && c.Data <= StopData &&
                          c.CenaBrutto == pozycje.CenaBrutto )
                       select c.Ilosc;

              if( p1.Count() > 0 )
              {
                pi = p1.Sum();
              }

              var r1 = from c in FormBigEaterCh.Ze.Rozchody
                       where
                         ( c.IdProduktu == pozycje.IdProduktu && c.Data > StartData && c.Data <= StopData &&
                          c.CenaBrutto == pozycje.CenaBrutto )
                       select c.Ilosc;

              if( r1.Count() > 0 )
              {
                ri = r1.Sum();
              }

              var s1 = from c in FormBigEaterCh.Ze.DniProdukty
                       where
                         ( c.IdProduktu == pozycje.IdProduktu && c.Data == StartData &&
                          c.CenaBrutto == pozycje.CenaBrutto )
                       select c.Ilosc;

              if( s1.Count() > 0 )
              {
                si = s1.Sum();
              }

              decimal suma = si + pi - ri;


              var dp = FormBigEaterCh.Ze.DniProdukty.CreateObject();
              dp.Data = dt;
              dp.CenaBrutto = pozycje.CenaBrutto;
              dp.IdProduktu = pozycje.IdProduktu;
              dp.Ilosc = suma;
              FormBigEaterCh.Ze.AddToDniProdukty(dp);


            }
        }
     }
     FormBigEaterCh.SaveDataBase();
     FormBigEaterCh.Ze.Refresh(System.Data.Objects.RefreshMode.StoreWins, FormBigEaterCh.Ze.DniProdukty);
      //}
      //catch( Exception ex)
      //{
      //  MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);
      //}

    }

    private void PrzychodyDataGridViewDefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
    {
      e.Row.Cells["dataColumn"].Value = _activeDay;
    }

    private void RozchodyDataGridViewDefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
    {
      e.Row.Cells["dataColumn1"].Value = _activeDay;
    }

    private void RozliczenieDataGridViewDefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
    {
      e.Row.Cells["dataColumn2"].Value = _activeDay;
    }

    private void przychodyDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
    {

    }

    private void przychodyDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void Button1Click(object sender, EventArgs e)
    {
      var eroz = new FormEditRozchody(_activeDay);
      eroz.ShowDialog();
      RefreshDataRozchody();
      Przelicz();
    }

    private void Button2Click(object sender, EventArgs e)
    {
      PrzeliczNastępne();
    }

    private void Button3Click(object sender, EventArgs e)
    {
      FormBigEaterCh.SaveDataBase();
      FormBigEaterCh.Ze.Refresh(System.Data.Objects.RefreshMode.StoreWins, FormBigEaterCh.Ze.Przychody);
      RefreshDataPrzychody();
      Przelicz();
    }

    private void Button4Click(object sender, EventArgs e)
    {
      FormBigEaterCh.SaveDataBase();
      FormBigEaterCh.Ze.Refresh(System.Data.Objects.RefreshMode.StoreWins, FormBigEaterCh.Ze.Rozchody);
      RefreshDataRozchody();
      Przelicz();
    }

    private void Button5Click(object sender, EventArgs e)
    {
      FormBigEaterCh.SaveDataBase();
      FormBigEaterCh.Ze.Refresh(System.Data.Objects.RefreshMode.StoreWins, FormBigEaterCh.Ze.Dni);
      RefreshRozliczenie();
      Przelicz();

    }

    private void libreOfficeToolStripMenuItem_Click(object sender, EventArgs e)
    {
      var ofd = new SaveFileDialog
      {
        Filter = @"*.ods|*.ods", DefaultExt = ".ods", AddExtension = true
      };
      ofd.FileName = string.Format("Raport {0}.ods", _activeDay.ToShortDateString());

      if( ofd.ShowDialog()==DialogResult.OK )
      {
        try
        {
          string[] d = new string[] { this.userDzien1.ActiveDay.ToString("dd.MM"), UserDzien.GetDayName(this.userDzien1.ActiveDay.DayOfWeek), string.Join(", ", this.userDzien1.GetPosilek(EnumPosilek.Sniadanie)), string.Join(", ", this.userDzien1.GetPosilek(EnumPosilek.Obiad)), string.Join(", ", this.userDzien1.GetPosilek(EnumPosilek.Podwieczorek)) };

          var inFile = new Uri(Path.Combine(System.Windows.Forms.Application.StartupPath, "raport.ods"));
          var outFile = new Uri(ofd.FileName);
          RaportExport.CreateRaport(inFile, outFile, d);
        }
        catch( Exception ex )
        {
          MessageBox.Show(ex.Message);
        }
        finally
        {
          MessageBox.Show(@"Eksport zakończono");
          Process.Start(ofd.FileName);
        }
      }

    }

  }
}
